<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘事件</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #box {
            /* margin: 0 auto; */
            /* margin-top: 150px; */
            width: 300px;
            height: 300px;
            position: relative;
            top: 150px;
            left: 450px;
            border: 1px solid #abcdef;
        }
        
        #angle {
            position: absolute;
            width: 30px;
            height: 30px;
        }
    </style>
</head>
<div id="box">
    <img id="angle" src="./img/head.jpg" alt="">
</div>

<body>

</body>

</html>
<script>
    let angle = window.document.querySelector('#angle');
    window.document.addEventListener('keydown', function(e) {
        let pos = 30;
        // 37 左
        // 38 上
        // 39 右
        // 40 下
        var x = angle.offsetLeft;
        var y = angle.offsetTop;
        switch (e.keyCode) {
            case 37:
                if (x >= 30 && x < 300) {
                    x -= pos;
                    angle.style.left = x + 'px';
                    angle.style.transform = 'rotate(270deg)';
                }
                break;
            case 38:
                if (y < 300 && y >= 30) {
                    y -= pos;
                    angle.style.top = y + 'px';
                    angle.style.transform = 'rotate(0deg)';
                }
                break;
            case 39:
                if (x >= 0 && x < 270) {
                    x += pos;
                    angle.style.left = x + 'px';
                    angle.style.transform = 'rotate(90deg)';
                }
                break;
            case 40:
                if (y < 270 && y >= 0) {
                    y += pos;
                    angle.style.top = y + 'px';
                    angle.style.transform = 'rotate(180deg)';
                }
                break;

            default:
                break;
        }
    });
</script>